package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class RefreshtokenInterceptor implements HandlerInterceptor {


    private StringRedisTemplate stringRedisTemplate;

    public RefreshtokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
////    1.获得session。
//        HttpSession session = request.getSession();
////        2.从session获得user。
//        Object user = session.getAttribute("user");
////        3.判断用户是否存在。
//        if (user == null) {
////            还没有登录。
//            response.setStatus(401);
//            return false;
//        }
//        UserHolder.saveUser((UserDTO) user);
//        return true;
//
////        从session中取出user，放入ThreadLocal中。

        String authorization = request.getHeader("authorization");
        if (authorization == null) {
            return true;
        }
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(RedisConstant.User_CODE_KEY + authorization);
        if (entries.isEmpty()) {
            return true;
        }

//        把hash数据h转为对象。
        UserDTO userDTO = BeanUtil.fillBeanWithMap(entries, new UserDTO(), false);
        UserHolder.saveUser(userDTO);

        stringRedisTemplate.expire(authorization, RedisConstant.User_CODE_TTL, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
